package com.trying.simpleioc.ioc;

import java.lang.reflect.Field;
import java.util.Map;

import com.trying.simpleioc.annotation.Inject;
import com.trying.simpleioc.util.ReflectionUtil;

public class IocHelper {
	private IocHelper(){}
	
	public static void init(){
		Map<Class<?>,Object> beanMap=BeanHelper.getBeanMap();
		
		if(!beanMap.isEmpty()){
			
			for(Map.Entry<Class<?>, Object> entry:beanMap.entrySet()){
				//获取当前要操作的‘类’ 和 对应的‘实例’
				Class<?> currentBeanClass=entry.getKey();
				Object currentBeanInstance=entry.getValue();
				
				Field[] beanFields=currentBeanClass.getDeclaredFields();
				if(beanFields!=null&&beanFields.length>0){
					
					for(Field field:beanFields){
						if(field.isAnnotationPresent(Inject.class)){
							//得到将要给‘当前bean’属性注入的 ‘目标实例’
							Class<?> injectClass=field.getType();
							Object injectInstance=beanMap.get(injectClass);
							if(injectInstance!=null){
								ReflectionUtil.setFeild(field,currentBeanInstance, injectInstance);
							}
						}
					}
				}
				
			}
			
		}
	}

}
